import React, { useState, useEffect } from 'react';
import { Button, Divider } from 'antd';
import { useHistory } from 'react-router-dom';
import { LogoutOutlined, HomeOutlined, LoadingOutlined, RollbackOutlined } from '@ant-design/icons';
import {
  openNotification_util, checkdatavalid_util_formdata, fetchsync_util,
  resultdata_to_formdata, addkey_for_mxdata,
  use_olreport_bybbbm,
  convertISODateTimeToYYYYMMDDHHMMSS,
} from '../util/util.js'
import Customfielditem_hook from '../newmes/customfielditem_hook.js'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { SaveOutlined } from '@ant-design/icons';
import logo from '../../../img/shipSRM/chlogo.png'
import { use_ckda_initformdata, use_ckda_view_initformdata } from './use_baseinfo_config.js';
import useStore from '../../useStore.js'
import { dropByCacheKey } from 'react-router-cache-route';

moment.locale('zh-cn')
var storage = window.localStorage;

const Ckda_form = () => {
  const history = useHistory();
  //动态数据源
  const [dynDatasObject, setdynDatasObject] = useState({
    query_ry: []
  })
  const [isloading, setisloading] = useState(false)

  //主表数据
  const [formdata, setformdata] = useState(JSON.parse(storage.pre_ckda_item).type == "edit" ||JSON.parse(storage.pre_ckda_item).type == "add" ? use_ckda_initformdata() : use_ckda_view_initformdata())
  const { nowroute, setnowroute,collapsed,setcollapsed } = useStore();
 
    //初始化树数据
    const init = async () => {  
      setisloading(true)
      var dictObj = await use_olreport_bybbbm([ "query_ry_glyh"])
      dynDatasObject.query_ry_glyh = dictObj.query_ry_glyh
      setdynDatasObject({ ...dynDatasObject })
      setisloading(false)
    }
  //加载主表数据
  const loadformdata = async (id) => {
    setisloading(true)
    let rtdata = await fetchsync_util("/admin/baseinfo/query_ckda_byid", 'POST', { id }, "json")
    rtdata.resultdata.formdata.create_time = rtdata.resultdata.formdata.create_time ? convertISODateTimeToYYYYMMDDHHMMSS(rtdata.resultdata.formdata.create_time) : ""
    rtdata.resultdata.formdata.update_time = rtdata.resultdata.formdata.update_time ? convertISODateTimeToYYYYMMDDHHMMSS(rtdata.resultdata.formdata.update_time) : ""
    setformdata({ ...formdata, ...resultdata_to_formdata(rtdata.resultdata.formdata, formdata) });
    init()
  }

  // 页面进入加载数据
  useEffect(() => {
    JSON.parse(storage.pre_ckda_item).type == "edit"||JSON.parse(storage.pre_ckda_item).type == "view" ? loadformdata(JSON.parse(storage.pre_ckda_item).data.id) : init()
  }, [])


  //设置value
  const setfield = (onekey, value, settype) => {
    if (settype == 'single') {
      var newitem = formdata[onekey]
      newitem.value = value
      let newformdata = Object.assign({}, formdata, { [onekey]: newitem });
      setformdata(newformdata)
    }
    else if (settype == "muti") {
      let [tansferarr, selectrow, newformdata] = [onekey, value, {}];
      tansferarr.forEach(item => {
        var newitem = formdata[item.target]
        newitem.value = selectrow ? selectrow[item.origin] : ""
        newformdata = Object.assign({}, formdata, { [item.target]: newitem });
      })
      setformdata(newformdata)
    }

  }

  

  const handleupload = async () => {


    var checkobj = checkdatavalid_util_formdata(formdata)
    //主表字段校验没通过不能保存，目前没写子表校验。
    
    if (!checkobj.rtstatus) { openNotification_util(checkobj.rtmessage);return; }
    else;
    //设置submit url
    var uploadurl = JSON.parse(storage.pre_ckda_item).type == "add" ?
      "/admin/baseinfo/add_ckda" : "/admin/baseinfo/update_ckda";
    let rtdata = await fetchsync_util(uploadurl, 'POST', { formdata }, "json")
    rtdata.rtstatus ? openNotification_util(rtdata.rtmessage) : 1
    setformdata(rtdata.resultdata.formdata);
    dropByCacheKey('ckda_list')
    dropByCacheKey('ckda_form')
    setnowroute({route:"/shipSRM/baseinfo/ckda_list",title:"仓库档案",closeroute:"/shipSRM/baseinfo/ckda_form"})

  }

  //返回列表
  const handleBackTolist = async () => {
    dropByCacheKey('ckda_list')
    dropByCacheKey('ckda_form')
    setnowroute({route:"/shipSRM/baseinfo/ckda_list",title:"仓库档案",closeroute:"/shipSRM/baseinfo/ckda_form"})
  }

  const renderfileditem = () => {
    var formdataarr = []
    for (var formitemkey in formdata) {
      formdata[formitemkey].inputType == "none" ? "" : formdataarr.push(formdata[formitemkey])
    }
    var renderstr = formdataarr.map(item => {
      var rtitem = item.input_type == "space_item" ?
        <Customfielditem_hook form={formdata} item={{ inputType: "none" }}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
        :
        <Customfielditem_hook form={formdata} item={formdata[item.dataIndex]}
          dynDatasObject={dynDatasObject}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
      return rtitem
    }
    )
    return renderstr
  }

  return (

    <div style={{    height: "94%", backgroundColor: `#F1F1F1`,right:"1%",top:"4vh",overflow:"hidden",
      backgroundSize: "100% 100%", width: collapsed?"94%":"84%", position: "absolute",  color: "white", fontSize: "0.8rem"}}
      data-page-type="form">

<div style={{width:"100%",height:"100%",backgroundColor:"white"}}>
      {isloading && (
           <div style={{
             position: 'absolute',
             top: '1%',
             left: 0,
             width: '100%',
             height: '98%',
             backgroundColor: 'rgba(0,0,0,0.1)',
             zIndex: 999
           }} />
        )}

      <div style={{
        width: "100%", height: "7%", position: "sticky", top: "1%",  backgroundColor: "white", color: "black", display: "flex",
        zIndex: 105, borderBottom: "2px solid #a91f24",
      }}>


      <div style={{ width: "40%", textAlign: "left", paddingRight: "1rem", display: "flex", alignItems: "center", fontWeight: "600" }}>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          工具栏
        </div>
        <div style={{ width: "60%", textAlign: "right", paddingRight: "1rem" }}>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          {JSON.parse(storage.pre_ckda_item).type !== "view" ?
          <Button type="primary" onClick={handleupload}
            style={{ width: "8vw", height: '2.2vw', fontSize: "1vw", borderRadius: "5px", marginTop: "0.4vw" }}>
          <SaveOutlined />{JSON.parse(storage.pre_ckda_item).type == "add" ? "保存" : "修改"}</Button>  
          :
        <Button type="default" onClick={handleBackTolist}
            style={{ width: "8vw", height: '2.2vw', fontSize: "1vw", borderRadius: "5px", marginTop: "0.4vw" }}>
          <RollbackOutlined />返回列表</Button>
        }
      </div>
      </div>

      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "98%", marginLeft: "1%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap"
        }}>
          {renderfileditem()}
        </div>
       

      </div>
      </div>
    </div>
  )
}


export default Ckda_form
var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `white`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
    topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
butdcstyle: { paddingLeft:"1vw",paddingRight:"1vw",height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
butmainstyle: {paddingLeft:"1vw", height: "2vw", position: "absolute", right: "6.5%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
butbackstyle: { borderRadius: "0.4rem", backgroundColor: "#a91f24", height: "2vw", position: "absolute", right: "12%", top: "0%",fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw"},
  kshcontainer: {
    width: "98%", position: "absolute", top: "10%", backgroundColor: "white", color: "#666",
    borderRadius: "10px",paddingBottom:"2rem",overflow:"hidden"
  },
}
